package spring_learn.a12;


import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;

/*
实现target类对应的代理类
 */
public class Proxy$Target  implements A12.foo{

    //在jdk的实现中，生成的代理类会继承proxy类，proxy类中有invocationHandler这个属性，所以只需要一个构造方法传入即可
    //具体可以看下面的proxy$target2类
    private  InvocationHandler invocationHandler;

    static final Method foo1;
    static final Method foo2;

    static {
        try {
            foo1 = A12.foo.class.getDeclaredMethod("foo1");
            foo2 = A12.foo.class.getDeclaredMethod("foo2");
        }catch (NoSuchMethodException e){
            throw new NoSuchMethodError(e.getMessage());
        }
    }

    public Proxy$Target(InvocationHandler invocationHandler) {
        this.invocationHandler=invocationHandler;
    }

    @Override
    public void foo1() {
        try {
            Object res = invocationHandler.invoke(this, foo1, new Object[0]);
        }catch (RuntimeException | Error e) {
        throw e;
        } catch (Throwable e) {
        throw new UndeclaredThrowableException(e);
         }
    }

    @Override
    public void foo2() {
        try {
            Object res = invocationHandler.invoke(this, foo2, new Object[0]);
        }catch (RuntimeException | Error e) {
            throw e;
        } catch (Throwable e) {
            throw new UndeclaredThrowableException(e);
        }
    }
}
